package com.ant.backstage.facade.exception;

import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;

/**
 * 异常信息统一处理类
 */
@RestControllerAdvice(basePackages = "com.ant.backstage.controller")
public class GlobalDefaultExceptionHandler {

	private static Logger logger = LogManager.getLogger(GlobalDefaultExceptionHandler.class);

	@ExceptionHandler()
	public ApiReturn handleException(Exception ex){
		ApiReturn apiReturn = new ApiReturn();
		//统一业务线日志唯一traceID
//		apiReturn.setTraceNo(logger.buildTracer().getTraceId());
		if (ex instanceof BackstageBusinessException) {
			BackstageBusinessException businessException = (BackstageBusinessException)ex;
			if (ApiReturnCode.HTTP_ERROR.getCode().equals(businessException.getCode())) {
				apiReturn.setMsg(ApiReturnCode.HTTP_ERROR.getMessage());
			} else {
				apiReturn.setMsg(businessException.getMsg());
			}
			apiReturn.setCode(businessException.getCode());
			logger.error("异常统一处理类,异常 code=[{}],msg=[{}]", businessException.getCode(), businessException.getMsg());
		} else if (ex instanceof IllegalArgumentException) {
			logger.error("异常统一处理类,异常信息 msg=[{}]", ex.getMessage());
		} else {
			logger.error("异常统一处理类,异常：", ex);
			apiReturn.setCode(ApiReturnCode.HTTP_ERROR.getCode());
			if (ex instanceof ServletException) {
				apiReturn.setMsg(ex.getMessage());
			} else {
				apiReturn.setMsg(ApiReturnCode.HTTP_ERROR.getMessage());
			}
			//暂时注释 防止dubbo引入项目 初始化shiro
			/*if (ex instanceof ShiroException){
				ShiroException shiroEX = (ShiroException)ex;
				apiReturn.setMsg(shiroEX.getMessage());
			}*/
		}
		return apiReturn;
	}

}
